import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QColor, QPainter, QLinearGradient, QBrush
from components.messageBox import CustomMessageBox  # 导入自定义提示框
from view.home import Home
from view.studenthome import StudentHome
from dao.index import LoginSchema
from view.devise import RoundedResetUI
from utils.json import JSONHandler


class AppManager:
    """管理应用程序启动和窗口的类"""
    def __init__(self):
        self.app = QApplication(sys.argv)  # 创建 QApplication 实例
        self.window = LoginWindow()        # 创建登录窗口实例

    def run(self):
        """启动应用程序"""
        self.window.show()                # 显示窗口
        sys.exit(self.app.exec_())         # 进入事件循环


class LoginWindow(QWidget):
    """登录窗口"""
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.drag_pos = QPoint()
        self.is_teacher = False  # 当前是否为教师模式
        self.json = JSONHandler('./config/cache.json')

    def initUI(self):
        # 窗口基本设置
        self.setFixedSize(400, 550)
        
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(30, 30, 30, 30)
        main_layout.setSpacing(20)

        # 关闭按钮（右上角）
        close_btn = QPushButton("×", self)
        close_btn.setFixedSize(30, 30)
        close_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: bold;
                border-radius: 15px;
            }
            QPushButton:hover {
                background-color: #FF0000;
            }
        """)
        close_btn.clicked.connect(self.close)
        close_btn.move(self.width() - 40, 10)

        # 学校信息（顶部居中）
        school_label = QLabel("欢迎", self)
        school_label.setAlignment(Qt.AlignCenter)
        school_label.setStyleSheet("font-size: 24px; color: #FFFFFF; font-weight: bold;")

        # 输入框
        self.user_input = QLineEdit()
        self.user_input.setPlaceholderText("学号")
        self.user_input.setMinimumHeight(40)
        
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("密码")
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setMinimumHeight(40)

        # 注册按钮和切换按钮
        bottom_btn_layout = QHBoxLayout()  # 使用 QHBoxLayout 水平排列按钮
        self.register_btn = QPushButton("注册")
        self.register_btn.setCursor(Qt.PointingHandCursor)
        self.toggle_btn = QPushButton("教师登录")
        self.toggle_btn.setCursor(Qt.PointingHandCursor)

        bottom_btn_layout.addWidget(self.register_btn)
        bottom_btn_layout.addWidget(self.toggle_btn)

        # 登录/注册按钮
        self.login_btn = QPushButton("登 录")
        self.login_btn.setCursor(Qt.PointingHandCursor)
        self.login_btn.setMinimumHeight(40)

        # 布局管理
        main_layout.addStretch(1)
        main_layout.addWidget(school_label)
        main_layout.addSpacing(20)
        main_layout.addWidget(self.user_input)
        main_layout.addWidget(self.password_input)
        main_layout.addLayout(bottom_btn_layout)  # 添加水平排列的按钮布局
        main_layout.addWidget(self.login_btn)
        main_layout.addStretch(1)

        self.setLayout(main_layout)

        # 信号连接
        self.register_btn.clicked.connect(self.toggle_register)
        self.toggle_btn.clicked.connect(self.toggle_user_type)
        self.login_btn.clicked.connect(self.auth_action)

        # 样式表
        self.setStyleSheet("""
            QLineEdit {
                border: 1px solid #E0E0E0;
                border-radius: 8px;
                padding: 8px 15px;
                font-size: 14px;
                background-color: rgba(255, 255, 255, 0.8);
            }
            QLineEdit:focus {
                border: 2px solid #00A3FF;
            }
            QPushButton {
                background-color: #00A3FF;
                color: white;
                font-size: 16px;
                font-weight: bold;
                border-radius: 8px;
            }
            QPushButton:hover {
                background-color: #0090E0;
            }
            QPushButton#toggle_btn {
                background-color: transparent;
                color: white;
                font-size: 14px;
                border: none;
                margin-left: 80px;
                padding: 5px 0 5px 10px;
            }
            QPushButton#toggle_btn:hover {
                text-decoration: underline;
            }
            QPushButton#register_btn {
                background-color: transparent;
                color: white;
                font-size: 14px;
                text-align: left;
                padding: 0;
            }
            QPushButton#register_btn:hover {
                text-decoration: underline;
            }
        """)
        self.toggle_btn.setObjectName("toggle_btn")
        self.register_btn.setObjectName("register_btn")

        # 添加忘记密码按钮（右下角）
        forget_btn = QPushButton("忘记密码", self)
        forget_btn.setStyleSheet("color: white; background: transparent; border: none;font-size: 14px;")
        forget_btn.adjustSize()  # 调整按钮尺寸以适应文本
        # 计算右下角坐标（右边距和下边距各10像素）
        x = self.width() - forget_btn.width() - 20
        y = self.height() - forget_btn.height() - 20
        forget_btn.move(x, y)
        forget_btn.clicked.connect(self.show_devise)
    
    def show_devise(self):
        """显示注册/修改密码窗口"""
        self.json.update("is_teacher", self.is_teacher)
        self.devise = RoundedResetUI()
        self.devise.show()


    def toggle_user_type(self):
        """切换用户类型（学生/教师）"""
        self.is_teacher = not self.is_teacher
        if self.is_teacher:
            self.toggle_btn.setText("我是学生")
            self.user_input.setPlaceholderText("教师工号")
        else:
            self.toggle_btn.setText("教师登录")
            self.user_input.setPlaceholderText("学号")

    def toggle_register(self):
        """切换注册/登录模式"""
        if self.login_btn.text() == "登 录":
            self.login_btn.setText("注 册")
        else:
            self.login_btn.setText("登 录")

    def auth_action(self):
        """认证按钮点击事件"""
        username = self.user_input.text()
        password = self.password_input.text()
        action = "注册" if self.login_btn.text() == "注 册" else "登录"

        # 模拟登录验证
        if self.check_login(username, password):
            self.close()
            self.json.update("user_id", username)
            if self.is_teacher:
                self.home = Home()
                self.home.show()
            else:
                self.student_home = StudentHome()
                self.student_home.show()
        else:
            self.show_error_message("用户名或密码错误！")

    def check_login(self, username, password) -> bool:
        print(f"正在验证用户 - 账号: {username}, 密码: {password}")
        schema = LoginSchema()
        islogin = False if self.login_btn.text() == "注 册" else True
        if islogin:
            if self.is_teacher:
                islogin = schema.get_teacher(user_id=username)
                if islogin and islogin["password"] == password:  # 验证密码
                    return True
                else:
                    return False
            else:
                islogin = schema.get_student(user_id=username)
                if islogin and islogin["password"] == password:  # 验证密码
                    return True
                else:
                    return False
        else:
            if self.is_teacher:
                ans = schema.register_teacher(user_id=username, password=password)
                if not ans: return False
            else:
                ans = schema.register_student(user_id=username, password=password)
                if not ans: return False
            return True

    def show_error_message(self, message):
        """显示无标题栏的扁平化提示框"""
        msg_box = CustomMessageBox(self)
        msg_box.show_error(message)

    def paintEvent(self, event):
        """绘制渐变背景"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = self.rect()
        gradient = QLinearGradient(0, 0, rect.width(), rect.height())
        gradient.setColorAt(0, QColor(135, 206, 250))
        gradient.setColorAt(1, QColor(221, 160, 221))
        painter.setBrush(QBrush(gradient))
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(rect, 15, 15)

    def mousePressEvent(self, event):
        """实现窗口拖动"""
        if event.button() == Qt.LeftButton:
            self.drag_pos = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        """实现窗口拖动"""
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self.drag_pos)
            event.accept()
